﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Collections;
using System.IO;
using MySql.Data.MySqlClient;
using System.Data.OleDb;
using h = functionService.shorts;
using da = functionService.DATECOD;
using fr = HK.FiscalRegistrar.FiscalRegistrar;
using vv = functionService.serfun_city7;
using rz = functionService.serfun_city7.rz;
using nameCod = functionService.nameCod;
using tol = city7.table.loadTables; 

namespace city7.table
{
    enum modeLoad {mainListSC }
    namespace loadTables
    {
        enum mainListSC { cod, izm, ves, vih, fpa, codrz }
    }
    public partial class FormTable : Form
    {
        
        functionService.prm_city q;
        rzpt.modeWAED currentMode;
        DataTable dts; modeLoad currentModeLoad;   //modeLookDoc currentModeLookDoc;
        reports currentReport;
        string sds, sdp, ds, ds1, dp, sm, codd, codo;
        string cod;
        public FormTable()
        {
            InitializeComponent();
        }
        public FormTable(int modeLoad0)
            : this()
        {
            InitializeComponentMy((modeLoad)modeLoad0);
        }

        private void InitializeComponentMy(modeLoad modeLoad0)
        {
            q = new functionService.prm_city(); //q.con.co(q.tk(ETALON.param.server_1)); q.tk

            string s = q.tk((int)ETALON.param.server_1);
            q.con.co(s);

            //ct = "888";
            sds = q.tk(ETALON.param.period_s_5);
            sdp = q.tk(ETALON.param.period_p_6);
            ds = Convert.ToDateTime(sds).Day.ToString();
            dp = Convert.ToDateTime(sdp).Day.ToString();
            ds1 = (h.i(ds) > 1 ? (h.i(ds) - 1) : 1).ToString();

            sm = q.tk(ETALON.param.kafe_smena_42).Substring(0, 3);
            currentModeLoad = modeLoad0; currentMode = city7.rzpt.modeWAED.work;
            load(currentModeLoad);

            setMode(city7.rzpt.modeWAED.work); set();

            vv.rz.currentColumn = 0;
            vv.rz.currentRow = 0;

            codd = "0";


        }
        
        void cellclick()
        {
            if (currentMode == city7.rzpt.modeWAED.add)
            {
                cellclick_Add();
            }
            else if (currentMode == city7.rzpt.modeWAED.edit)
            {
                cellclick_edit();
            }
            else if (currentMode == city7.rzpt.modeWAED.delete)
            {
                cellclick_delete();
            }
            else if (currentMode == city7.rzpt.modeWAED.work)
            {
                cellclick_work();
            }
            else if (currentMode == city7.rzpt.modeWAED.non)
            {

            }
        }

        #region cellclick_edit_mainListSC
        private bool cellclick_edit_mainListSC_fi1(object[] fi)
        {
            // ETALON.listAnyEdit f = new ETALON.listAnyEdit("city", "mainListSC", "cod<3000");
            /*<cod>3</cod>  <name>гр;шт;мл</name>  <prim>тип при загрузке изм</prim>
              <cod>4</cod>  <name>ТС;ГП;ПФ</name>....*/
            ETALON.WORK.FormTXT f = new ETALON.WORK.FormTXT(nameCod.readName (fi[(int)tol.mainListSC.cod].ToString())); 
            f.ShowDialog();
            string cod = nameCod.readCod(fi[(int)tol.mainListSC.cod].ToString());
            
            if (f.textBox1.Text.Length>0)
            {
                string newText = nameCod.name_cod(f.textBox1.Text, cod);
                dataGridView1.SelectedCells[0].Value = newText;
                fi[(int)tol.mainListSC.cod] = newText; return true;
            }
            else return false;
        }
        private bool  cellclick_edit_mainListSC_fi2(object[] fi)
        {
            // ETALON.listAnyEdit f = new ETALON.listAnyEdit("city", "mainListSC", "cod<3000");
            /*<cod>3</cod>  <name>гр;шт;мл</name>  <prim>тип при загрузке изм</prim>
              <cod>4</cod>  <name>ТС;ГП;ПФ</name>....*/
            city7.lists.FormFilters f = new city7.lists.FormFilters(3);
            f.ShowDialog();
            if (f.IsOk)
            {
                dataGridView1.SelectedCells[0].Value = f.valueSelect;
                fi[(int)tol.mainListSC.izm] = f.valueSelect; return true;
            }
            else return false;
        }
        private bool cellclick_edit_mainListSC_fi3(object[] fi)
        {
            // ETALON.listAnyEdit f = new ETALON.listAnyEdit("city", "mainListSC", "cod<3000");
            /*<cod>3</cod>  <name>гр;шт;мл</name>  <prim>тип при загрузке изм</prim>
              <cod>4</cod>  <name>ТС;ГП;ПФ</name>....*/
            ETALON.FormKolZakaz f = new ETALON.FormKolZakaz(); f.ShowDialog();
                if (f.IsSelect)
                {
                  dataGridView1.SelectedCells[0].Value = f.valueEnter;
                  fi[(int)tol.mainListSC.ves] = f.valueEnter; return true;
                }
                else return false;
        }
        private bool cellclick_edit_mainListSC_fi4(object[] fi)
        {
            ETALON.FormKolZakaz f = new ETALON.FormKolZakaz(); f.ShowDialog();
            if (f.IsSelect)
            {
                dataGridView1.SelectedCells[0].Value = f.valueEnter;
                fi[(int)tol.mainListSC.vih] = f.valueEnter; return true;
            }else return false;
        }
        private int FPA_mainListSC(object fpa)
        {
            if (fpa.ToString() == "ГП") return 1;
            else if (fpa.ToString() == "ТС") return 0;
            else return 2;
        }
        private bool cellclick_edit_mainListSC_fi5(object[] fi)
        {
            ArrayList ar = new ArrayList();
            ar.Add("Технологическое сырье /ТС/ (0)");
            ar.Add("Готовая продукция /ГП/ (1)");
            ar.Add("Полуфабрикат /ПФ/ (2)");
            ar.Add("Сырье для пробы /СП/ (3)");
            ETALON.listAny f = new ETALON.listAny(ar);
            //city7.lists.FormFilters f = new city7.lists.FormFilters(4);
            f.ShowDialog();
            if (f.IsOk)
            {
                dataGridView1.SelectedCells[0].Value = f.sCod ; //FPA_mainListSC(f.valueSelect);
                fi[(int)tol.mainListSC.fpa] = f.sCod; return true;//FPA_mainListSC(f.valueSelect); 
            }
            else return false;
        }
        private bool cellclick_edit_mainListSC_fi6(object[] fi)
        {
            ETALON.listAnyEdit f = new ETALON.listAnyEdit("city", "list_sc", true); 
            f.ShowDialog();
            if (f.IsOK)
            {
                dataGridView1.SelectedCells[0].Value = f.sText;
                fi[(int)tol.mainListSC.codrz] = f.sText; return true;
            }
            else return false;
        }
        private void cellclick_edit_mainListSC(int xx, int yy)
        {
           // cod = nameCod.readCod(dataGridView1.Rows[yy].Cells[0].Value.ToString());
            bool IsSelect = false;
            string sql_dml = "";

                    object[] fi = new object[6]
                    {
                            dataGridView1.Rows[yy].Cells[(int)tol.mainListSC.cod].Value,
                            dataGridView1.Rows[yy].Cells[(int)tol.mainListSC.izm ].Value,
                            dataGridView1.Rows[yy].Cells[(int)tol.mainListSC.ves ].Value,
                            dataGridView1.Rows[yy].Cells[(int)tol.mainListSC.vih ].Value,
                            dataGridView1.Rows[yy].Cells[(int)tol.mainListSC.fpa ].Value,
                            dataGridView1.Rows[yy].Cells[(int)tol.mainListSC.codrz].Value,
                    };

                    //h.m(string.Concat(fi[0],fi[1],fi[2],fi[3],fi[4],fi[5]));
            /*select city.name_cod(t.name, t.cod) as cod,
             * t.izm, 
             * t.ves, t.vih, t.fpa,
             * city.name_cod(tt.name, t.codrz) as codrz
 from m2_list_sc t*/

            //string sql = "", kolFaktOst = "0";

            if (xx == 0)  //наименование продукции
            {
                IsSelect = cellclick_edit_mainListSC_fi1(fi);
            }
            else if (xx == 1) //изм
            { IsSelect = cellclick_edit_mainListSC_fi2(fi); }
            else if (xx == 2) //вес
            { IsSelect = cellclick_edit_mainListSC_fi3(fi); }
            else if (xx == 3) //вых
            { IsSelect = cellclick_edit_mainListSC_fi4(fi); }
            else if (xx == 4) //фпа
            { IsSelect = cellclick_edit_mainListSC_fi5(fi); }
            else if (xx == 5) //наименование продукции рец
            {
                IsSelect = cellclick_edit_mainListSC_fi6(fi);
            }

            if (IsSelect)
            {
                sql_dml = string.Concat(
                    "UPDATE list_sc SET",
                    "  name= '", nameCod.readName ( fi[(int)tol.mainListSC.cod].ToString()),
                    "',  izm='", fi[(int)tol.mainListSC.izm],
                    "', ves=", fi[(int)tol.mainListSC.ves],
                    ", vih=", fi[(int)tol.mainListSC.vih],
                    ", fpa=", fi[(int)tol.mainListSC.fpa],
                    ", codrz=",nameCod.readCod ( fi[(int)tol.mainListSC.codrz].ToString()),
                    " WHERE cod = ", nameCod.readCod(fi[(int)tol.mainListSC.cod].ToString()), " ;"
                    );
                q.UpdateData(sql_dml );
            }
            //else if (xx == 6) //расход за период
            //{

            //}
            //else if (xx == 7) //ост конечные
            //{ }
            //else if (xx == 8) //ост фактические
            //{
            //    ETALON.FormKolZakaz f = new ETALON.FormKolZakaz(); f.ShowDialog();
            //    if (f.IsSelect)
            //    {
            //        kolFaktOst = f.valueEnter;
            //        oof = o - Convert.ToDouble(kolFaktOst);
            //        if (oof >= 0)
            //        {
            //            createDocNkAktRashod_Prihod(4);
            //            dataGridView1.SelectedCells[0].Value = kolFaktOst;
            //            //load(xx,yy);
            //            //hh.m(hh.aa("Создаем расход ", oof));
            //        }
            //        else if (oof < 0)
            //        {
            //            oof = -oof;
            //            createDocNkAktRashod_Prihod(1);
            //            dataGridView1.SelectedCells[0].Value = kolFaktOst;
            //            //load(xx,yy);
            //            //hh.m(hh.aa("Создаем приход ", oof));
            //        }

            //        string s111 = string.Concat("call `hand_set123`('city.sir_td_z', 'cod123');");
            //        q.UpdateData(s111);
            //    }
            //}
            //else if (xx == 9) //fpa
            //{ }
            //else if (xx == 10) //ct
            //{ }
        }
        #endregion

        private void cellclick_delete()
        {
            
            if (currentMode == city7.rzpt.modeWAED.delete)
            {
                int xx = dataGridView1.SelectedCells[0].ColumnIndex;
                int yy = dataGridView1.SelectedCells[0].RowIndex;
                object cod = "";
                if (currentModeLoad == modeLoad.mainListSC)
                {
                    cod = nameCod.readCod_int(dataGridView1.Rows[yy].Cells[(int)tol.mainListSC.cod].Value.ToString());
                    f_del_mainListSC(cod);
                    load(modeLoad.mainListSC);
                }
            }

        }
        private void cellclick_edit()
        {
            int xx = dataGridView1.SelectedCells[0].ColumnIndex;
           // object y = dataGridView1.SelectedCells[0].Value;
            int yy = dataGridView1.SelectedCells[0].RowIndex;
           // object osc = dataGridView1.Rows[yy].Cells[0].Value;

            if (currentModeLoad == modeLoad.mainListSC)
            {
                cellclick_edit_mainListSC(xx, yy);
            }
        }
        void f_del_mainListSC(object codo)
        {
            string sql =
               string.Concat("delete from list_sc WHERE cod =", codo, ";");
            if (MessageBox.Show("Удаление!", "Подтвердите Ваше намерение", MessageBoxButtons.OKCancel)
                == DialogResult.OK)
            {
                q.UpdateData(sql);
            }
        }

        void f_add_mainListSC(object whereCondition0)
        {
           // string name = nameo.ToString().Replace("(", "/").Replace(")", "/");
            int ic = Convert.ToInt32(q.selectScalar(string.Concat("select count(*) as cc from  city.list_sc WHERE ", whereCondition0, ";")));
            int imm = 1;
            if (ic > 0)
            {
                imm = Convert.ToInt32
                    (q.selectScalar
                    (
                     string.Concat("select max(cod)+1 as codm from city.list_sc WHERE ", whereCondition0, ";")
                     )
                    );
            }
            //cod, name,izm,ves,fpa,codrz
            ETALON.WORK.FormTXT f = new ETALON.WORK.FormTXT("Наименование"); f.ShowDialog();
            string text0="-";
            if (f.textBox1.Text.Length > 0)
            {
                text0 = f.textBox1.Text;
            }
            string sql = string.Concat("INSERT  city.list_sc (cod, name,izm,ves,fpa,codrz) VALUES (",
                imm, ", '", text0 ,"', 'гр', 1, 0, ",  imm,");");
            q.UpdateData(sql);

        }
        private void cellclick_Add()
        {
            if (currentModeLoad == modeLoad.mainListSC)
            {
                f_add_mainListSC("cod>0"); load(modeLoad.mainListSC);
            }
        }
        private void cellclick_work()
        {
            //select 
            //name_cod(name,ct) as name, o, p, r, osn, pp, rp, osk, osk-rad+pad as osf, fpa, ct 
            //from ost0;


            //int xx = dataGridView1.SelectedCells[0].ColumnIndex;
            //object y = dataGridView1.SelectedCells[0].Value;
            //int yy = dataGridView1.SelectedCells[0].RowIndex;
            //object obj = dataGridView1.Rows[yy].Cells[0].Value;


            string sql = "";
            if (currentModeLoad  == modeLoad.mainListSC )
            {
                //int yy = dataGridView1.SelectedCells[0].RowIndex;
                //object obj = dataGridView1.Rows[yy].Cells[0].Value;// H.m(obj);
                //codd = obj.ToString();
                //object ocodo = dataGridView1.Rows[yy].Cells[2].Value; codo = functionService.nameCod.readCod(ocodo.ToString());
                //currentOpro = opro.look_doc;
                //load(opro.look_doc);


            }
            else 
            {
                
            }
            
        }

        void set()
        {
            if (currentModeLoad == modeLoad.mainListSC )
            {
                #region mainListSC

                /*select city.name_cod(t.name, t.cod) as cod, t.izm, t.ves, t.vih, t.fpa,city.name_cod(tt.name, t.codrz) as codrz
 from m2_list_sc t*/
                dataGridView1.Columns[0].Width = 240;
                dataGridView1.Columns[1].Width = 40;
                dataGridView1.Columns[2].Width = 60;
                dataGridView1.Columns[3].Width = 60;
                dataGridView1.Columns[4].Width = 30;
                dataGridView1.Columns[5].Width = 240;


                dataGridView1.Columns[0].HeaderText = "Наим1";
                dataGridView1.Columns[1].HeaderText = "Изм";
                dataGridView1.Columns[2].HeaderText = "Вес";
                dataGridView1.Columns[3].HeaderText = "Вых";
                dataGridView1.Columns[4].HeaderText = "ФПА";
                dataGridView1.Columns[5].HeaderText = "Наим2";

                #endregion
            }
        }
        void setMode(rzpt.modeWAED mo)
        {
            currentMode = mo;
            if (mo == city7.rzpt.modeWAED.work)
            {
                setColor(Color.LightGray, Color.White);
                dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
                // refresh();
            }
            else if (mo == city7.rzpt.modeWAED.add)
            {
                setColor(Color.SkyBlue, Color.LightSkyBlue);
                dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect ;
                cellclick_Add();
            }
            else if (mo == city7.rzpt.modeWAED.edit)
            {
                setColor(Color.LightGreen, Color.LightSkyBlue);
                dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
            }
            else if (mo == city7.rzpt.modeWAED.delete)
            {
                setColor( Color.DarkRed,Color.DarkOrange );
                dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            }
            else if (mo == city7.rzpt.modeWAED.non)
            {

            }

        }
        void setColor(Color c1, Color c2)
        {
            if (currentModeLoad == modeLoad.mainListSC )
            {
                #region mainListSC
                dataGridView1.Columns[0].DefaultCellStyle.BackColor = c2;
                dataGridView1.Columns[1].DefaultCellStyle.BackColor = c1;
                dataGridView1.Columns[2].DefaultCellStyle.BackColor = c1;
                dataGridView1.Columns[3].DefaultCellStyle.BackColor = c1;
                dataGridView1.Columns[4].DefaultCellStyle.BackColor = c1;
                dataGridView1.Columns[5].DefaultCellStyle.BackColor = c2;
                //dataGridView1.Columns[6].DefaultCellStyle.BackColor = c2;
                //dataGridView1.Columns[7].DefaultCellStyle.BackColor = c1;
                #endregion
            }
         
        }
        void load(modeLoad mo)
        {

            string sql = ""; object ss = "";
            if (mo == modeLoad.mainListSC ) //-главный списов продукции сырья и пф
            {/*select city.name_cod(t.name, t.cod) as cod, t.izm, t.ves, t.vih, t.fpa,city.name_cod(tt.name, t.codrz) as codrz
 from m2_list_sc t
left join m2_list_sc tt on t.codrz=tt.cod;*/
                sql = string.Concat("call `city`.`m2_mainSC` ();"); //H.m(sql);
                dts = q.selectAny(sql); dataGridView1.DataSource = dts;
            }
            else 
            {

            }
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            toolStripMenuItem2_Click_fun();
        }
        public void toolStripMenuItem2_Click_fun()
        {
            //  string[] aa = 
            //string[] aa = new string[]
            //    {
            //    "Наименование0", "Наименование1", "КолР1",
            //    "Наименование2", "Кол2", "КолВых2",
            //    "Наименование2с", "КолР2", "Наименование3", "Кол3", "КолВ3", "Наименование3с", "КолР3",
            //    "Наименование4", "Кол4", "КолВ4", "КолР4", "Наименование", "КолРасх", "КодТ"
            //    };



            SaveFileDialog SV = new SaveFileDialog();
            SV.Filter = "MSExcel files (*.xls)|*.xls|All files (*.*)|*.*";
            SV.FilterIndex = 1;
            SV.RestoreDirectory = true;
            if (SV.ShowDialog() == DialogResult.OK)
            {
                saveDataXLS(SV.FileName.ToString());
                MessageBox.Show(string.Concat("Экспорт в файл ", SV.FileName.ToString(), " успешно завершен."));
            }
        }
        public void saveDataXLS(string filePath)
        {


            string file_path = filePath;
            int clmns = dataGridView1.Columns.Count;
            Int32 rows = dataGridView1.Rows.Count;
            Int32 i = 0;
            Int32 i1 = 0;
            string clType = "String";//"String";

            string[] aa = new string[clmns];
            for (int j = 0; j < clmns; j++) { aa[j] = dataGridView1.Columns[j].HeaderText; }


            System.IO.StreamWriter file = new System.IO.StreamWriter(file_path);
            file.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            file.WriteLine("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"");
            file.WriteLine(" xmlns:x=\"urn:schemas-microsoft-com:office:excel\"");
            file.WriteLine(" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"");
            file.WriteLine(" xmlns:html=\"http://www.w3.org/TR/REC-html40\">");
            file.WriteLine(" <Styles>");
            file.WriteLine("  <Style ss:ID=\"s21\">");
            file.WriteLine("   <NumberFormat ss:Format=\"Fixed\"/>");
            file.WriteLine("  </Style>");
            file.WriteLine(" </Styles>");
            file.WriteLine(" <Worksheet ss:Name=\"Table1\">");
            file.WriteLine("  <Table>");
            file.WriteLine("   <Row>");
            for (i = 0; i < clmns; i++)
            {
                file.WriteLine(string.Concat("    <Cell><Data ss:Type=\"String\">", aa[i], "</Data></Cell>"));
            }
            file.WriteLine("   </Row>");
            for (i1 = 0; i1 < rows; i1++)
            {
                file.WriteLine("   <Row>");
                for (i = 0; i < clmns; i++)
                {
                    file.WriteLine(string.Concat("    <Cell><Data ss:Type=\"", clType, "\">", dataGridView1.Rows[i1].Cells[i].Value, "</Data></Cell>"));
                }
                file.WriteLine("   </Row>");
            }
            file.WriteLine("  </Table>");
            file.WriteLine(" </Worksheet>");
            file.WriteLine("</Workbook>");
            file.Close();
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            setMode(city7.rzpt.modeWAED.edit);
        }

        private void toolStripDropDownButton2_Click(object sender, EventArgs e)
        {
            setMode(city7.rzpt.modeWAED.work); refresh();
        }

        void refresh()
        {
            dataGridView1.DataSource = dts;
        }


        private void toolStripTextBox1KeyUp()
        {
            
                DataView dv = new DataView(dts); //H.m(30);
                try
                {
                    //h.m(h.aa(e.KeyCode,e.KeyData,e.KeyValue ));
                    //if (e.KeyValue.ToString() == "222") { toolStripTextBox1.Text = ""; }
                    //else
                    //{
                        dv.RowFilter = string.Concat("cod like '%", toolStripTextBox1.Text, "%'");
                        dataGridView1.DataSource = dv;
                    //}
                }
                catch { }
                
        }
        private void toolStripTextBox2KeyUp()
        {
            DataView dv = new DataView(dts); //H.m(30);
            dv.RowFilter = string.Concat("codrz like '%", toolStripTextBox2.Text, "%'");
            dataGridView1.DataSource = dv;
        }

        private void toolStripTextBox1_KeyUp(object sender, KeyEventArgs e)
        {
            toolStripTextBox1KeyUp();
        }

        private void toolStripTextBox2_KeyUp(object sender, KeyEventArgs e)
        {
            toolStripTextBox2KeyUp();
        }

        private void toolStripDropDownButton4_Click(object sender, EventArgs e)
        {
            setMode(city7.rzpt.modeWAED.add);
        }

        private void toolStripDropDownButton5_Click(object sender, EventArgs e)
        {
            setMode(city7.rzpt.modeWAED.delete);
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            cellclick();
        }
    }
}
